<?php
/**
 * @Description:
 * @Author: Chern
 * @Date: 2023/6/28
 * @Time: 17:03
 */

namespace app\model;

use app\branch;
use app\controller\SystemOrganizationalStructure;
use app\stateData;
use think\db\Where;
use think\facade\Db;
use think\Model;
use think\model\concern\SoftDelete;

class User extends Model
{
    use SoftDelete;

    protected $name;

    const LEVEL_ZERO = 0;
    //admin
    const LEVEL_ONE = 1;
    //总公司
    const LEVEL_TWO = 2;
    //分支
    const LEVEL_THREE = 3;

//    protected $autoWriteTimestamp = 'timestamp';

    protected $createTime = 'create_date';
    protected $deleteTime = 'delete_time';


//    public function organization()
//    {
//        return $this->hasMany(UserOrganization::class,'id','department_id');
//    }
//    public function position()
//    {
//        return $this->hasMany(UserPosition::class,'id','level_id');
//    }

    /**
     * @param $value
     * @return string
     * @throws \Exception
     */
    public function setSaltAttr($value)
    {
        return bin2hex(random_bytes(8));
    }

    /**
     * @param $value
     * @return string
     */
    public function setPasswordAttr($value)
    {
        return md5($value);
    }

    /**
     * @param $value
     * @return false|string
     */
//    public function setHireDateAttr($value)
//    {

//        return date('Y-m-d,H:i:s', $value);
//    }

    /**
     * @param $value
     * @return false|string
     */
    public function setResignationDateAttr($value)
    {
        return date('Y-m-d,H:i:s', $value);
    }


    public function getCompanyIdAttr($name): array
    {
        return [
            'id' => $name,
            'text' => (new UserOrganization())->getStructureName($name) ?: ''
        ];
    }

    public function getDepartmentIdAttr($name)
    {
        return [
            'id' => $name,
            'text' => (new UserOrganization())->getStructureName($name) ?: ''
        ];
    }

    public function getLevelIdAttr($name): array
    {
        return [
            'id' => $name,
            'text' => (new UserPosition())->getLevelName($name) ?: ''
        ];
    }

    public function getUpImgAttr($value)
    {
        if (!$value) {
            //默认头像
            $value = branch::$avatar;
        }
        return str_replace('\\', '/', 'http://' . $_SERVER['HTTP_HOST'] . '/storage/' . $value);
    }

    public function getHireDateAttr($name)
    {
        if (empty($name) || $name == '0000-00-00 00:00:00') return "";
        return $name;
    }

    public function userInfo($id)
    {
        return self::where('id', $id)->find();
    }

    /**
     * @param $data
     * @return string|void
     * @throws \Exception
     */
    public static function onBeforeInsert($data)
    {
        if (!is_array($data)) {
            $data = $data->toArray();
        }
        if (!array_key_exists('salt', $data)) {

            return $data['salt'] = bin2hex(random_bytes(8));
        }
    }

    /**
     * @param $query
     * @param $value
     * @return void
     */
    public function searchUsernameAttr($query, $value): void
    {
        $query->where('username', 'like', $value . '%');
    }

    /**
     * 根据账号密码查询用户信息
     * @param $username
     * @param $password
     * @return User|array|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserData($username, $password)
    {
        return $this->where(['username' => $username, 'password' => $password])->find();
    }

    /**
     * 验证账号是否存在
     * @param $username
     * @return \app\model\User|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserAccData($username)
    {
        return $this->where(['username' => $username])->find();
    }

    /**
     * 查询指定类型用户  0:员工 1:admin 2:总公司账号  3:分公司账号
     * @param $type
     * @param  $page
     * @return User[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */

    public function getUserInfo($type, $pageNum, $page, $like = '')
    {
        $where = [
            ['username', 'like', '%' . $like . '%'],
            ['type', '=', $type]
        ];

        $where2 = [
            ['nickname', 'like', '%' . $like . '%'],
            ['type', '=', $type]
        ];
        //分支管理列表将数据通过创建时间倒序
        return $this->whereOr([$where, $where2])->page($page, $pageNum)->order('create_date desc')->select();
    }

    /**
     * 计算分类账号数量
     * @param $type
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function getUserTypeCount($type)
    {
        return $this->where(['type' => $type])->count();
    }

    /**
     * 根据条件匹配值
     */
    public function getWhereUser($where, $whereOr = '', $page = 1, $pageNum = 1)
    {
        return $this->where($where)->where($whereOr)->page($page, $pageNum)->select();
    }

    /**
     * 根据条件匹配值总数
     */
    public function getWhereUserCount($where, $whereOr)
    {
        return $this->where($where)->where($whereOr)->count();
    }


    /**
     * 获取所有用户name id
     * @return \app\model\User[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserNameList()
    {

        return $this->where('type', '>', '2')->field('username,id')->select();
    }

    public function getPeopleAss($type)
    {
        return User::where(['type' => $type])->field(['username', 'id'])->select();
    }

    /**
     * 获取某个用户的username
     * @param $id
     * @return mixed
     */
    public function getIdName($id)
    {
        return User::where(['id' => $id])->value("nickname");
    }

    /**
     * 获取某个用户的Nickname
     * @param $id
     * @return mixed
     */
    public function getIdNickName($id)
    {

        return User::where(['id' => $id])->value("nickname");
    }

    /**
     * 获取某个用户的id
     * @param $nickname
     * @return mixed
     */
    public function getNameId($nickname)
    {
        return $this->where(['nickname' => $nickname])->value("id");
    }

    /**
     * 获取nickname部门ID
     * @param $nickname
     * @return mixed
     */
    public function getOrgIdModel($nickname)
    {
        return $this->where(['nickname' => $nickname])->value('department_id');
    }

    /**
     * 根据用户id查询用户信息
     * @param $id
     * @return User[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */

    public function getIdUserData($id)
    {
        return User::where(['id' => $id])->find();
    }

    /**
     * 修改系统信息
     * 主管理账号可以操作
     * @param $nickname
     * @param $password
     * @param $type
     * @return User
     */
    public function systemSave($data): User
    {
        return self::Update($data);
    }

    /**
     * 添加分支账号
     * @param $data
     * @param $type
     * @return User|Model
     */
    public function addBranchCompanyAccount($data, $type)
    {
        $data = array_merge($data, array('type' => $type));
        return self::create($data);
    }


    /**
     * 检查username唯一性
     * @param $product_name
     * @param $id
     * @return bool
     */
    public function checkUniqueName($username, $id = null)
    {
        $info = self::fetchSql(false)
            ->where('username', $username)
            ->whereNull('delete_time');
        $info = $info->find();
        if (!$id) {
            if ($info) {
                return false;
            } else {
                return true;
            }
        } else {
            if ($info) {
                if ($info['id'] == $id) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        }
    }
    public function checkUniqueBranchDepartment($department_id, $id = null)
    {
        $info = self::fetchSql(false)
            ->where('department_id', $department_id)
            ->where('type', self::LEVEL_THREE)
            ->whereNull('delete_time');
        $info = $info->find();
        if (!$id) {
            if ($info) {
                return false;
            } else {
                return true;
            }
        } else {
            if ($info) {
                if ($info['id'] == $id) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        }
    }

    /**
     * 修改分支账号
     * @param $data
     * @return User
     */
    public function editBranchCompanyInfo($data)
    {
        $data['create_date'] = date('Y-m-d H:i:s');

        return self::Update($data, ['id' => $data['id']]);

    }

    /**
     * 重置密码
     * @param $id
     * @param $password
     * @return User
     */
    public function rePassword($id, $password)
    {
        return self::Update(['password' => $password], ['id' => $id]);
    }

    /**
     * 删除账号
     * @param $id
     * @return bool
     */
    public function delBranchAccount($id)
    {

        return self::destroy($id);
    }

    /**
     * 修改用户信息
     * @param $data
     * @return User
     */
    public function editUserdata($data)
    {
        return User::update($data);
    }

    /**
     * 查询用户信息
     * @param $uid
     * @return User|array|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserLevelInfoModel($uid)
    {
        return (new User)->find($uid);
    }

    public function getDepartmentIdsUserIds($department_ids)
    {
        return $this->where('department_id', 'in', $department_ids)->column('id');
    }


    /**
     * 查询部门成员
     * @param $oid
     * @return \app\model\User[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrgUserListModel($oid, $where, $page, $pageNum)
    {
        return $this->where('department_id', 'in', $oid)->where($where)->page($page, $pageNum)->select();
    }

    public function getOrgUserCountModel($oid, $where)
    {
        return $this->where('department_id', 'in', $oid)->where($where)->count();
    }

    public function getOrgUserPageListModel($oid, $pageNum, $page)
    {
        return $this->whereIn('department_id', $oid)->page($page, $pageNum)->select();
    }

    public function getOrgUserFieldModel($oid)
    {
        return $this->where(['department_id' => $oid])->field('id,nickname')->select()->toArray();
    }

//    public function getOrgUserCountModel($oid): int
//    {
//        return $this->where(['department_id' => $oid])->count();
//    }

    /**
     * 根据id批量查询用户信息
     * @param $array
     * @return \app\model\User[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getIdUserRandInfo($where)
    {
//        return $this->whereIn('id', $where)->where('is_k', '=', '0')->select();
        return $this->whereIn('id', $where)->select();
    }

    public function getIdUserFieldRandInfo($idArr,$page,$pageNum,$startDate,$endDate)
    {
        $startDate .= "00:00:00";
        $endDate .= "23:59:59";
        $OrderEnterpriseCompanyModel = new OrderEnterpriseCompany();
        $OrderEnterpriseExchangeModel = new OrderEnterpriseExchange();
        $OrderOtherCertificateBusinessModel = new OrderOtherCertificateBusiness();
        $OrderEnterpriseCertificateBusinessModel = new OrderEnterpriseCertificateBusiness();

        if (empty($page)){
            $data = $this->whereIn('id', $idArr)
//                ->where('type', '=', '0')
//                ->where('is_k', '=', '0')
                ->field('id,nickname,department_id,is_k_op_date')
                ->select()->toArray();
        }else{
            $data = $this->whereIn('id', $idArr)
//            ->where('type', '=', '0')
//            ->where('is_k', '=', '0')
                ->field('id,nickname,department_id,is_k_op_date')
                ->page ($page,$pageNum)
                ->select()->toArray();
        }

        /**
         * 处理关闭账号问题
         */
        $userData = [];
        foreach ($data as $datum) {
            if ($datum['is_k_op_date'] === "0000-00-00 00:00:00"){
                $userData[] = $datum;
            }else{
                if (strtotime ($startDate) <= strtotime ($datum['is_k_op_date']) || strtotime ($endDate) <= strtotime ($datum['is_k_op_date'])){
                    $userData[] = $datum;
                }else{
                    /**
                     * 如果离职之后有业绩产生继续统计
                     */
                    //查询证书注册是否有该离职人员业绩
                    if ($OrderEnterpriseCompanyModel->whereIn('status',[1,2,3,4,5])
                        ->whereFindInSet ('performance_uid',$datum['id'])
                        ->where ('performance','>',0)
                        ->whereBetweenTime ('sale_date',$startDate,$endDate)
                        ->select ()->toArray ()){
                        $userData[] = $datum;
                        continue;
                    }

                    //查询倒证是否有该离职人员业绩
                    if ($OrderEnterpriseExchangeModel->whereIn('status',[1,2,3,4,5])
                        ->whereFindInSet ('performance_uid',$datum['id'])
                        ->where ('performance','>',0)
                        ->whereBetweenTime ('sale_date',$startDate,$endDate)
                        ->select ()->toArray ()){
                        $userData[] = $datum;
                        continue;
                    }
                    //查询证书办理是否有该离职人员业绩
                    if ($OrderOtherCertificateBusinessModel->whereIn('status',[1,2])
                        ->where ('performance_uid',$datum['id'])
                        ->where ('performance','>',0)
                        ->whereBetweenTime ('sale_date',$startDate,$endDate)
                        ->select ()->toArray ()){
                        $userData[] = $datum;
                        continue;
                    }
                    //查询企业证书是否有该离职人员业绩
                    if ($OrderEnterpriseCertificateBusinessModel->whereIn('status',[1,2])
                        ->whereFindInSet ('performance_uid',$datum['id'])
                        ->where ('performance','>',0)
                        ->whereBetweenTime ('sale_date',$startDate,$endDate)
                        ->select ()->toArray ()){
                        $userData[] = $datum;
                    }
                }
            }
        }

        return $userData;
    }

    public function getIdUserCountInfo($idArr,$startDate,$endDate)
    {
        $startDate .= "00:00:00";
        $endDate .= "23:59:59";

        $OrderEnterpriseCompanyModel = new OrderEnterpriseCompany();
        $OrderEnterpriseExchangeModel = new OrderEnterpriseExchange();
        $OrderOtherCertificateBusinessModel = new OrderOtherCertificateBusiness();
        $OrderEnterpriseCertificateBusinessModel = new OrderEnterpriseCertificateBusiness();

        $data = $this->whereIn('id', $idArr)
//            ->where('type', '=', '0')
//            ->where('is_k', '=', '0')
            ->field('id,nickname,department_id,is_k_op_date')
            ->select ()->toArray ();

        $num = 0;
        foreach ($data as $item) {
            if ($item['is_k_op_date'] === "0000-00-00 00:00:00"){
                $num++;
            }else{
                if (strtotime ($startDate) <= strtotime ($item['is_k_op_date']) || strtotime ($endDate) <= strtotime ($item['is_k_op_date'])){
                    $num++;
                }else{
                    /**
                     * 如果离职之后有业绩产生继续统计
                     */
                    //查询证书注册是否有该离职人员业绩
                    if ($OrderEnterpriseCompanyModel->whereIn('status',[1,2,3,4,5])
                        ->whereFindInSet ('performance_uid',$item['id'])
                        ->where ('performance','>',0)
                        ->whereBetweenTime ('sale_date',$startDate,$endDate)
                        ->select ()->toArray ()){
                        $num++;
                        continue;
                    }

                    //查询倒证是否有该离职人员业绩
                    if ($OrderEnterpriseExchangeModel->whereIn('status',[1,2,3,4,5])
                        ->whereFindInSet ('performance_uid',$item['id'])
                        ->where ('performance','>',0)
                        ->whereBetweenTime ('sale_date',$startDate,$endDate)
                        ->select ()->toArray ()){
                        $num++;
                        continue;
                    }
                    //查询证书办理是否有该离职人员业绩
                    if ($OrderOtherCertificateBusinessModel->whereIn('status',[1,2])
                        ->where ('performance_uid',$item['id'])
                        ->where ('performance','>',0)
                        ->whereBetweenTime ('sale_date',$startDate,$endDate)
                        ->select ()->toArray ()){
                        $num++;
                        continue;
                    }
                    //查询企业证书是否有该离职人员业绩
                    if ($OrderEnterpriseCertificateBusinessModel->whereIn('status',[1,2])
                        ->whereFindInSet ('performance_uid',$item['id'])
                        ->where ('performance','>',0)
                        ->whereBetweenTime ('sale_date',$startDate,$endDate)
                        ->select ()->toArray ()){
                        $num++;
                    }


                }
            }
        }
        return $num;
    }

    /**
     * 查询levle是否有人
     * @param $id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPotionData($id): bool
    {
        return (bool)$this->where(['level_id' => $id])->select()->toArray();
    }

    /**
     * 查询level下面所有人id
     * @param $levelId
     * @return array
     */
    public function getPotionIdDataModel($levelId)
    {
        return $this->where(['level_id' => $levelId])->column('id');
    }

    /**
     *
     * @param  $where
     * @return array
     */
    public function getFIdResult($where = ''): array
    {
        return $this->where($where)->whereNotIn('username', 'admin')->where('is_k', 0)->column('id');
    }

    public function getOidUidDataModel($oidArr)
    {
        return $this->whereIn('department_id', $oidArr)->whereNotIn('username', 'admin')->column('id');
    }

    /**
     * 获取某个部门下所有人员信息
     * @param $oid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOidUidSelectDataModel($oid)
    {
        return $this->where('department_id', $oid)->select()->toArray();
    }


    /**
     * 查询用户部门
     * @param $id
     * @return mixed
     */
    public function getUidOrgId($id)
    {
        return $this->where(['id' => $id])->value('department_id');
    }

    /**
     * 获取用户职位等级
     * @param $uid
     * @return mixed
     */
    public function getUidLevelIdModel($uid)
    {
        return $this->where(['id' => $uid])->value('level_id');
    }


    /**
     * 查询部门下的用户名称id
     * @param $id
     * @return \app\model\User[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getIdTitle($id)
    {
        return $this->where(['department_id' => $id])->where('is_k', 0)->field('id,nickname as title')->select();

    }

    /**
     * 修改用户签名 || 主题色
     * @param $id
     * @param $param
     * @return \app\model\User
     */
    public function setSignTextModel($id, $param)
    {
        return $this->where(['id' => $id])->update($param);
    }

    /**
     * 设置主题色
     * @param $id
     * @param $param
     * @return \app\model\User
     */
    public function setColorModel($id, $param)
    {
        return $this->where(['id' => $id])->update($param);
    }

    /**
     * 获取id用户部门 id 昵称
     * @return array
     */
    public function getAllUserIdNicknameOrgModel($idArr): array
    {
        return $this->whereIn('id', $idArr)->where('type', '=', 0)->field('id,nickname,department_id')->where('is_k', 0)->select()->toArray();
    }

    /**
     * 获取部门下面所有人
     * @param $oid
     * @return array
     */
    public function getOrgUidModel($oid)
    {
        return $this->where(['department_id' => $oid, 'type' => 0])->where('is_k', 0)->column('id,nickname');
    }

    public function getOrgArrUidModel($oidArr)
    {
        return $this->whereIn('department_id', $oidArr)->where('is_k', 0)->where(['type' => 0])->column('id,nickname');
    }

    /**
     * 根据id数组查询
     * @param $str
     * @return array
     */
    public function getUidArrNicknameModel($idArr)
    {
        if (!is_array($idArr)) {
            $idArr = explode(',', $idArr);
        }
        return $this->whereIn('id', $idArr)->where('is_k', 0)->column('id,nickname');
    }

    /**
     * 获取所有部门相关人员id
     * @param $idArr
     * @return array
     */
    public function getUidArrDataModel($idArr): array
    {
        return $this->whereIn('department_id', $idArr)->whereNotIn('username', 'admin')->where('is_k', 0)->column('id');
    }

    /**
     * 获取所有用户公司集合
     * @return mixed
     */
    public function getGroupCompany()
    {
//        return $this->where(['type' => 0, 'is_k' => 0])->field('company_id')->group('company_id')->select()->toArray();
        return $this->where(['type' => 0])->field('company_id')->where('is_k', 0)->group('company_id')->select()->toArray();
    }

    /**
     * 获取所有用户部门集合
     * @return mixed
     */
    public function getGroupOrgModel()
    {
//        return $this->where(['type' => 0, 'is_k' => 0])->field('department_id')->group('department_id')->select()->toArray();
        return $this->where(['type' => 0])->field('department_id')->where('is_k', 0)->group('department_id')->select()->toArray();
    }

    /**
     * 获取所有用户姓名集合
     * @return mixed
     */
    public function getGroupUidModel()
    {
//        return $this->where(['type' => 0, 'is_k' => 0])->field('id,nickname')->group('id')->select()->toArray();
        return $this->where(['type' => 0])->field('id,nickname')->where('is_k', 0)->group('id')->select()->toArray();
    }

    /**
     * 获取分支绑定的所有部门
     * @return mixed
     */
    public function getBranchDepartmentIds()
    {
        return self::fetchSql(false)->where('type', self::LEVEL_THREE)->select()->toArray();
    }

    public function getDepartmentUserList($department_ids)
    {
        return self::fetchSql(false)
            ->where('department_id', 'in', $department_ids)
            ->whereNull('delete_time')
//            ->where('is_k', 0)
            ->field('id,nickname')
            ->select()
            ->toArray();
    }

    /**
     * 获取某个部门下的部门下所有人
     * @param $department_ids
     * @return mixed
     */
    public function getDepartmentUserIdList($department_ids)
    {
        return self::fetchSql(false)
            ->where('department_id', 'in', $department_ids)
            ->whereNull('delete_time')
            ->where('is_k', 0)
            ->column('id');
    }

    /**
     * 获取财务审批人
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getIsSpUidModel()
    {
        return $this->where(['is_sp' => 2])->select()->toArray();
    }

    /**
     * 获取特价证书审批人
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getIsTjzsUidModel()
    {
        return $this->where(['is_tjzs_sp' => 2])->select()->toArray();
    }

    public function getWhereInData($whereInOne, $whereInTwo)
    {
        return $this->whereIn('department_id', $whereInOne)->whereIn('level_id', $whereInTwo)->select()->toArray();
    }

    public function getUserDepartmentId($uid)
    {
        return $this->where('id',$uid)->value('department_id');
    }

    /**
     * 获取所有正常用户ID
     */
    public function getAllUidModel()
    {
        return $this->where (['type'=>0,'is_k'=>0])->column ('id');
    }

    /**
     * 获取所有UID
     * @return array
     */
    public function getAllUidsModel()
    {
        return $this->where (['type'=>0])->column ('id');
    }
}